Page({
  data: {
    bookDetail: {
      title: '百年孤独',
      author: '加西亚·马尔克斯',
      cover: '/images/covers/book1.jpg',
      intro: '魔幻现实主义文学代表作...',
      audioUrl: 'https://example.com/audio.mp3'
    },
    progress: 0,
    isPlaying: false,
    playbackRate: 1.0,
    currentChapter: 1,
    isNightMode: false
  },

  onLoad(options) {
    this.audioCtx = wx.createInnerAudioContext()
    this.audioCtx.src = this.data.bookDetail.audioUrl
    
    this.audioCtx.onTimeUpdate(() => {
      this.setData({
        progress: (this.audioCtx.currentTime / this.audioCtx.duration * 100).toFixed(2)
      })
    })
    // 在onLoad中添加
    this.audioCtx.onWaiting(() => {
      this.setData({ isLoading: true })
    })

    this.audioCtx.onCanplay(() => {
      this.setData({ isLoading: false })
    })

    // 添加缓冲进度监听
    this.audioCtx.onProgress = () => {
      this.setData({
        bufferProgress: (this.audioCtx.buffered / this.audioCtx.duration * 100).toFixed(2)
      })
    }
  },

  togglePlay() {
    if (this.data.isPlaying) {
      this.audioCtx.pause()
    } else {
      this.audioCtx.play()
    }
    this.setData({ isPlaying: !this.data.isPlaying })
  },

  changePlaybackRate() {
    const rates = [1.0, 1.25, 1.5, 2.0]
    const newRate = rates[(rates.indexOf(this.data.playbackRate) + 1) % rates.length]
    this.audioCtx.playbackRate = newRate
    this.setData({ playbackRate: newRate })
  },

  switchChapter(e) {
    const chapter = e.currentTarget.dataset.chapter
    this.setData({ currentChapter: chapter })
  },

  toggleNightMode() {
    this.setData({ isNightMode: !this.data.isNightMode })
  },

  onUnload() {
    this.audioCtx.stop()
    this.audioCtx.destroy()
  }
})